package com.dianda.generic.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dianda.generic.commons.global.DataMap;
import com.dianda.generic.commons.global.StaticCaches;
import com.dianda.generic.dao.pojo.LoginInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by The_Answer on 2016/6/14.
 * 返回报文构建工具
 */
public class ResponseUtils {

    public static List<Map<String, Object>> getPostParamsByJsonStringForArray(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength == 0) return null;
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        String json = new String(buffer, charEncoding);
        JSONArray jsonArray = JSON.parseArray(json);
        List<Map<String, Object>> rs = new ArrayList<>();
        for (int i = 0, len = jsonArray.size(); i < len; i++) {
            JSONObject job = jsonArray.getJSONObject(i);
            Map<String, Object> data = new DataMap<>();
            for (Map.Entry<String, Object> entry : job.entrySet()) {
                data.put(entry.getKey(), entry.getValue());
            }
            rs.add(data);
        }
        return rs;
    }

    public static Map<String, Object> getPostParamsByJsonString(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength == 0) return null;
        byte[] buffer = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {
            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        String json = new String(buffer, charEncoding);
        JSONObject jobj = JSONObject.parseObject(json);
        Map<String, Object> data = new DataMap<>();
        for (Map.Entry<String, Object> entry : jobj.entrySet()) {
            data.put(entry.getKey(), entry.getValue());
        }
        return data;
    }

    private static JSONObject createResponseBody(boolean isSuccess, String message, Object... datas) {
        JSONObject result = new JSONObject();
        result.put("status", isSuccess ? "success" : "error");
        result.put("message", message);
        if (datas != null && datas.length > 0) {
            if (datas.length == 1) {
                result.put("data", datas[0]);
            } else {
                List<Object> data = new ArrayList<>();
                Collections.addAll(data, datas);
                result.put("data", data);
            }
        }
        return result;
    }

    /**
     * @param message 需要传递的信息
     * @param datas   需要传递的数据（可以为多个）
     * @return 构建处理成功的Json对象
     */
    public static JSONObject createSuccessResponseBody(String message, Object... datas) {
        return createResponseBody(true, message, datas);
    }

    /**
     * @param datas 需要传递的数据（可以为多个）
     * @return 构建处理成功的Json对象
     */
    public static JSONObject createSuccessResponseBody(Object... datas) {
        return createSuccessResponseBody("处理成功", datas);
    }

    public static JSONObject createErrorResponseBody() {
        return createSuccessResponseBody("trace failed");
    }

    /**
     * @param message 需要传递的信息
     * @param datas   需要传递的数据（可以为多个）
     * @return 构建处理失败的Json对象
     */
    public static JSONObject createErrorResponseBody(String message, Object... datas) {
        return createResponseBody(false, message, datas);
    }
    
    /**
     * @param request Http请求对象
     * @return 将Request中的parameter取出来封装成Map返回
     */
    public static Map<String, Object> createRequestParamsMap(HttpServletRequest request) {
        if (!StaticCaches.POSTMAN_MODE) try {
            return getPostParamsByJsonString(request);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        Map<String, Object> rs = new DataMap<>();
        Enumeration<String> elmts = request.getParameterNames();
        while (elmts.hasMoreElements()) {
            String nextStr = elmts.nextElement();
            try {
                rs.put(nextStr.trim(), new String(request.getParameter(nextStr).getBytes("ISO-8859-1"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }
    
    /**
     * @param request Http请求对象
     * @return 将Request中的parameter取出来封装成Map返回
     */
    public static Map<String, Object> createRequestParamsMapNew(HttpServletRequest request) {
        Map<String, Object> rs = new DataMap<>();
        Enumeration<String> elmts = request.getParameterNames();
        while (elmts.hasMoreElements()) {
            String nextStr = elmts.nextElement();
            rs.put(nextStr.trim(), request.getParameter(nextStr));
        }
        return rs;
    }

    public static Map<String, Object> createRequestAndSessionLoginInfo(HttpServletRequest request) {
        Map<String, Object> rs = createRequestParamsMap(request);
        ObjectMapper mapper=new ObjectMapper();
        LoginInfo loginInfo = (LoginInfo) request.getSession().getAttribute("userinfo");
        rs.put("userinfo", loginInfo);
        return rs;
    }
}
